#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：back 
@File    ：task_dao.py
@IDE     ：PyCharm 
@Author  ：七分是你
@Date    ：2024/6/29 上午10:31 
@explain : 
"""
from app.dao.models import XlxTask, XlxTaskRecord
from . import tools
from .base_dao import getDatabaseSession


class TaskQueryDao(object):
    """任务查询DAO"""

    @classmethod
    def select(cls, mode_name: str = 'Task', field_names: list = None, **kwargs) -> list[XlxTask] | list[XlxTaskRecord]:
        with getDatabaseSession() as session:
            mode = XlxTask
            if mode_name == 'Record':
                mode = XlxTaskRecord
            if field_names:
                valid_fields = [getattr(mode, field_name, None) for field_name in field_names if
                                hasattr(mode, field_name)]
                if not valid_fields:
                    raise ValueError("No valid fields to select.")
                query = session.query(*valid_fields)
            else:
                query = session.query(mode)
            query = tools.build_query(query, mode, **kwargs)
            result = query.all()
        return result

    @classmethod
    def get_count(cls, mode_name: str = 'Task', **kwargs) -> int:
        with getDatabaseSession() as session:
            mode = XlxTask
            if mode_name == 'Record':
                mode = XlxTaskRecord
            query = session.query(mode)
            query = tools.build_query(query, mode, **kwargs)
            count = query.count()
        return count


class TaskOperateDao(object):
    """任务操作DAO"""

    @classmethod
    def save_task_record(cls, data: list[dict]):
        with getDatabaseSession() as session:
            task_records = [XlxTaskRecord(**task_data) for task_data in data]
            session.add_all(task_records)
